<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">添加角色</el-button>

    <!--表格区域-->
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="code" label="角色编码" width="200" />
      <el-table-column align="center" prop="name" label="角色名" width="150" />
      <el-table-column align="header-center" prop="remarks" label="角色描述" />
      <el-table-column label="状态" class-name="status-col" width="100">
        <template v-slot="{row}">
          <el-switch
            v-model="row.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="handleState(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250px">
        <template v-slot="{row}">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleAuth(row)">分配权限</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加 / 编辑表单-->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'添加角色'">
      <el-form ref="dataForm" :model="role" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="role.code" placeholder="角色编码" />
        </el-form-item>
        <el-form-item label="角色名" prop="name">
          <el-input v-model="role.name" placeholder="角色名" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="role.remarks"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="dialogType==='create'?createData():updateData()">继续</el-button>
      </div>
    </el-dialog>

    <!--分配权限-->
    <el-dialog :visible.sync="dialogAuthVisible" title="分配权限" :before-close="handleClose">
      <el-tree
        ref="authTree"
        :data="routes"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />
      <div style="text-align:right;">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="assignAuth">分配</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { addRole, updateRole, getRoleList, createRole, updateRoleById, deleteRoleById, assignAuthById } from '@/api/role'
import { getAuthList } from '@/api/authority'

// 默认角色参数
const defaultRole = {
  code: '',
  name: '',
  remarks: '',
  routes: []
}

export default {
  data() {
    return {
      // 角色信息表单
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      // 添加编辑对话框状态
      dialogVisible: false,
      // 添加编辑对话框类型
      dialogType: 'create',
      // 表单校验规则
      rules: {
        code: [
          {
            required: true,
            message: '请输入角色编码',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入角色名',
            trigger: 'blur'
          }
        ]
      },
      // 分配权限对话框状态
      dialogAuthVisible: false,
      // 树形控件配置选项
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // 角色id
      roleId: undefined
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // 从服务器获取所有路由和角色列表
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    // 获取路由表
    async getRoutes() {
      getAuthList().then(res => {
        this.routes = res.data
        // console.log(res.data)
      })
      // this.routes = this.generateRoutes(res.data)
    },
    // 获取角色表
    async getRoles() {
      const res = await getRoleList()
      this.rolesList = res.data
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) {
          continue
        }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    // 处理添加角色
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      this.dialogType = 'create'
      this.dialogVisible = true
    },
    // 添加角色
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createRole(this.role).then((res) => {
            this.dialogVisible = false
            // 获取角色列表
            this.getRoles()
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.role = deepClone(row)
    },
    // 修改角色状态
    handleState(row) {
      updateRoleById(row).then((res) => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
        .catch(() => {
          row.state = !row.state
        })
    },
    // 更新角色信息
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.role)
          updateRoleById(tempData).then((res) => {
            this.dialogVisible = false
            // 获取角色列表
            this.getRoles()
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 处理分配权限
    handleAuth(row) {
      this.dialogAuthVisible = true
      this.$nextTick(() => {
        this.$refs.authTree.setCheckedKeys(row.authIds)
      })
      this.roleId = row.id
    },
    // 分配权限
    assignAuth() {
      const ids = this.$refs.authTree.getCheckedKeys()
      let str = ''
      ids.forEach(id => {
        str += id + ','
      })
      str = str.substring(0, str.length - 1)
      const data = {
        id: this.roleId,
        authorityId: str
      }
      assignAuthById(data).then(res => {
        this.getRoles()
        this.dialogAuthVisible = false
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    handleClose() {
      this.dialogAuthVisible = false
      this.$refs.authTree.setCheckedKeys([])
    },
    // 处理删除角色
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色,是否继续?', 'Warning', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(row)
        })
        .catch(() => {
          this.$notify({
            title: '提示',
            message: '已取消删除',
            type: 'info',
            duration: 2000
          })
        })
    },
    // 删除角色信息
    deleteData(row) {
      deleteRoleById(row.id).then(res => {
        this.getRoles()
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    // 确认表单
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

      if (isEdit) {
        await updateRole(this.role.key, this.role)
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].key === this.role.key) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        const { data } = await addRole(this.role)
        this.role.key = data.key
        this.rolesList.push(this.role)
      }

      const { description, key, name } = this.role
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>Role Key: ${key}</div>
            <div>Role Name: ${name}</div>
            <div>Description: ${description}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/component/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
